from django.contrib.auth.decorators import permission_required
from django.utils.decorators import method_decorator
from rest_framework.permissions import IsAdminUser
from rest_framework.views import APIView
from rest_framework.response import Response
from meiduo_admin.serializers.users import AdminAuthSerializer,UserSerializer
from rest_framework import status
# from meiduo_mall.meiduo_mall.apps.meiduo_admin.serializers.users import AdminAuthSerializer

# # POST /meiduo_admin/authorizations/
# class AdminAuthorizeView(APIView):
#     def post(self, request):
#         """管理员登录"""
#         # ① 获取参数并进行校验
#         serializer = AdminAuthSerializer(data=request.data)
#         serializer.is_valid(raise_exception=True)
#
#         # ② 服务器生成 jwt token 数据
#         # 调用序列化器类中的 create，将生成 JWT token 的代码抽取到了序列化器类的 create 方法中
#         serializer.save()
#
#         # ③ 返回响应
#         return Response(serializer.data, status=status.HTTP_201_CREATED)
from users.models import User

'''优化代码'''
from rest_framework.generics import CreateAPIView

# POST /meiduo_admin/authorizations/
class AdminAuthorizeView(CreateAPIView):
    # 指定当前视图所使用的序列化器类
    serializer_class = AdminAuthSerializer

# class UserInfoView(APIView):
#     # 指定权限：只有管理员用户才能进行访问
#     permission_classes = [IsAdminUser]
#
#     def get(self, request):
#         '''普通用户数据查询'''
#         # ① 获取keyword关键字
#         keyword = request.query_params.get('keyword')
#
#         # ② 查询普通用户数据
#         if keyword:
#             users = User.objects.filter(is_staff=False, username__contains=keyword)
#         else:
#             users = User.objects.filter(is_staff=False)
#
#         # ③ 将用户数据序列化并返回
#         serializer = UserSerializer(users, many=True)
#         return Response(serializer.data)

from rest_framework.generics import GenericAPIView
'''修改后'''
# GET /meiduo_admin/users/?page=<页码>&pagesize=<页容量>&keyword=<搜索内容>
class UserInfoView(GenericAPIView):
    # 指定权限：只有管理员才能进行访问
    permission_classes = [IsAdminUser]
    # 指定视图所使用的序列化器类
    serializer_class = UserSerializer

    def get_queryset(self):
        '''返回视图所使用的查询集'''
        # ① 获取 keyword 关键字
        # self.request：获取请求对象
        keyword = self.request.query_params.get('keyword')

        # ② 查询普通用户数据
        if keyword:
            users = User.objects.filter(is_staff=False, username_conta=keyword)
        else:
            users = User.objects.filter(is_staff=False)

        return users
    def get(self, request):
        '''普通用户数据查询'''
        # ① 查询趋同用户数据
        users = self.get_queryset()

        # ② 将用户数据序列化并返回
        serializer = self.get_serializer(users, many=True)
        return Response(serializer.data)

    @method_decorator(permission_required('users.view_user_api', raise_exception=True))
    def get(self, request, *args, **kwargs):
        return super().get(request, *args, **kwargs)